package cn.chinaflame.pagodas.service;

import cn.chinaflame.pagodas.dto.VwAgentAreaItemDto;
import cn.chinaflame.pagodas.entity.PaAgent;
import cn.chinaflame.pagodas.entity.VwAgentAreaItem;
import cn.chinaflame.pagodas.entity.YwItem;
import cn.chinaflame.pagodas.enums.CodeEnum;
import cn.chinaflame.pagodas.repository.PaAgentRepository;
import cn.chinaflame.pagodas.repository.VwAgentAreaItemRepository;
import cn.chinaflame.pagodas.repository.YwItemRepository;
import cn.chinaflame.pagodas.req.VwAgentAreaItemReq;
import cn.chinaflame.pagodas.utils.ParamPreconditions;
import cn.chinaflame.pagodas.utils.TreeUtils;
import com.google.common.base.Strings;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * @author created by lbq
 * @date 2018年1月6日 下午3:31:11
 **/
@Service
public class VwAgentAreaItemService {
    private static final Logger log = LoggerFactory.getLogger(VwAgentAreaItemService.class);

    @Autowired
    private VwAgentAreaItemRepository vwAgentAreaItemRepository;
    @Autowired
    private PaAgentRepository paAgentRepository;
    @Autowired
    private YwItemRepository ywItemRepository;

    public List<VwAgentAreaItem> query(VwAgentAreaItemReq req) {
        log.info("查询代理、省、市、项目信息req:{}", req);
        List<VwAgentAreaItem> entityList = vwAgentAreaItemRepository.findAll(new Specification<VwAgentAreaItem>() {
            @Override
            public Predicate toPredicate(Root<VwAgentAreaItem> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
                List<Predicate> list = Lists.newArrayList();
                if (!Strings.isNullOrEmpty(req.getAgentId()))
                    list.add(cb.equal(root.get("agentId").as(String.class), req.getAgentId()));
                if (!Strings.isNullOrEmpty(req.getParentAgentId()))
                    list.add(cb.equal(root.get("parentAgentId").as(String.class), req.getParentAgentId()));
                if (!Strings.isNullOrEmpty(req.getProvinceCode()))
                    list.add(cb.equal(root.get("provinceCode").as(String.class), req.getProvinceCode()));
                if (!Strings.isNullOrEmpty(req.getCityCode()))
                    list.add(cb.equal(root.get("cityCode").as(String.class), req.getCityCode()));
                if (!Strings.isNullOrEmpty(req.getAreaCode()))
                    list.add(cb.equal(root.get("areaCode").as(String.class), req.getAreaCode()));
                if (!Strings.isNullOrEmpty(req.getItemId()))
                    list.add(cb.equal(root.get("itemId").as(String.class), req.getItemId()));
                Predicate[] p = new Predicate[list.size()];
                return cb.and(list.toArray(p));
            }
        });
        return entityList;
    }

    public List<Map<String, String>> queryByMap(VwAgentAreaItemReq req) {
        log.info("查询代理、省、市、项目信息req:{}", req);
        List<VwAgentAreaItem> entityList = vwAgentAreaItemRepository.findAll(new Specification<VwAgentAreaItem>() {
            @Override
            public Predicate toPredicate(Root<VwAgentAreaItem> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
                List<Predicate> list = Lists.newArrayList();
                if (!Strings.isNullOrEmpty(req.getAgentId()))
                    list.add(cb.equal(root.get("agentId").as(String.class), req.getAgentId()));
                if (!Strings.isNullOrEmpty(req.getParentAgentId()))
                    list.add(cb.equal(root.get("parentAgentId").as(String.class), req.getParentAgentId()));
                if (!Strings.isNullOrEmpty(req.getProvinceCode()))
                    list.add(cb.equal(root.get("provinceCode").as(String.class), req.getProvinceCode()));
                if (!Strings.isNullOrEmpty(req.getCityCode()))
                    list.add(cb.equal(root.get("cityCode").as(String.class), req.getCityCode()));
                if (!Strings.isNullOrEmpty(req.getAreaCode()))
                    list.add(cb.equal(root.get("areaCode").as(String.class), req.getAreaCode()));
                if (!Strings.isNullOrEmpty(req.getItemId()))
                    list.add(cb.equal(root.get("itemId").as(String.class), req.getItemId()));
                Predicate[] p = new Predicate[list.size()];
                return cb.and(list.toArray(p));
            }
        });
        List<Map<String, String>> resultList = Lists.newArrayList();
        for (int i = 0; i < entityList.size(); i++) {
            Map<String, String> map = Maps.newHashMap();
            map.put("ProjectID", entityList.get(i).getItemId());
            map.put("ProjectName", entityList.get(i).getItemName());
            map.put("ProvinceCode", entityList.get(i).getProvinceCode());
            map.put("ProvinceName", entityList.get(i).getProvinceName());
            map.put("CityCode", entityList.get(i).getCityCode());
            map.put("CityName", entityList.get(i).getCityName());
        }
        return resultList;
    }

    public VwAgentAreaItemDto queryByTree(VwAgentAreaItemReq req) {
        log.info("查询代理、省、市、项目树形结构req:{}", req);
        req.setAgentId(null);
        ParamPreconditions.checkNotEmpty(req.getAgentId(), CodeEnum.FAIL.getCode(), "代理id不能为空");
        PaAgent rootAgent = paAgentRepository.findOne(req.getAgentId());
        YwItem rootItem = ywItemRepository.queryByAgentId(rootAgent.getId());
        VwAgentAreaItem root = new VwAgentAreaItem();
        root.setAgentId(rootAgent.getId());
        root.setAgentName(rootAgent.getName());
        if (!Objects.isNull(rootItem))
            root.setItemName(rootItem.getName());
        List<VwAgentAreaItem> result = query(req);
        result.add(root);
        List<VwAgentAreaItemDto> dtos = Lists.newArrayList();
        VwAgentAreaItemDto parentDto = new VwAgentAreaItemDto();
        BeanUtils.copyProperties(root, parentDto);
        for (VwAgentAreaItem areaItem : result) {
            VwAgentAreaItemDto dto = new VwAgentAreaItemDto();
            BeanUtils.copyProperties(areaItem, dto);
            dtos.add(dto);
        }
        TreeUtils.createTree(dtos, parentDto, "agentId", "parentAgentId", "children");
        return parentDto;
    }

}








